import React, { Component } from 'react';
import { Modal, Form, Input, InputNumber, Cascader, DatePicker, Select, Row, Col,
        message, Table, Radio, Button, Tooltip, Icon  } from 'antd';
import { campanys, custPropertys, industrys } from '../../utils/config';
import Toggles from '../../components/Toggles';
import moment from 'moment';
const FormItem = Form.Item;
const RadioGroup  = Radio .Group;
const InputGroup = Input.Group;

class AddModal extends Component {

  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      disabled:false,
    };
  }

  showModalHandler = (e) => {

    if (e) e.stopPropagation();
    this.setState({
      disabled:typeof(this.props.onOk)==='object' ? true : false,
    });
    if(this.props.show){
      this.setState({
        visible: true,
      });
      return;
    }
    if(!this.props.selectedRows){
      message.warning('请选择一条数据！',2)
      return;
    }else if(this.props.selectedRows.length<1){
      message.warning('请选择一条数据！',2)
      return;
    }else if(this.props.selectedRows.length>1){
      message.warning('该操作只允许选择一条数据！',2)
      return;
    }

    this.setState({
      visible: true,
    });
  };


  hideModalHandler = () => {
    this.setState({
      visible: false,
    });
  };

  okHandler = () => {
    const { onOk } = this.props;

    this.props.form.validateFields((err, values) => {
      this.props.selectedRows.length>0 && (values.id = this.props.selectedRows[0].id);
      values.customerId && (values.customerId = values.customerId[0]);
      // values.isFocusInsurance && (values.isFocusInsurance = values.isFocusInsurance[0]);
      // values.isPhoneCall && (values.isPhoneCall = values.isPhoneCall[0]);
      // values.isSocialSecurityLarge && (values.isSocialSecurityLarge = values.isSocialSecurityLarge[0]);
      // values.signParty && (values.signParty = values.signParty[0]);
      // values.unilateral && (values.unilateral = values.unilateral[0]);
      // values.send && (values.send = values.send[0]);
      values.operator = localStorage.getItem('userName')||'';

      if(this.state.disabled){
        this.setState({
          visible: false,
        });
        return;
      }
      if (!err) {
        onOk(values);
        this.hideModalHandler();
        this.props.form.resetFields();
      }
    });
  };

  render() {
    const { children, } = this.props;
    const customerList = this.props.customerList || [];
    const { getFieldDecorator } = this.props.form;
    const selectedRows = this.props.selectedRows || [];
    const { id, customerId, sonId, serverId, product, price, cost, serviceDescription, effectiveTime,
            deadTime, status, ladderQuotation, priceTerms, operator, createTime, modifyTime, customerNum,
            customerName, startPerson, abortPerson, sonPrice, sonCost, description, name, genre, reimbursementRatio,
            insuredAmount, deductible, subsidyAmount, numberDayIndemnity, quota, serverDescription,} = selectedRows[0] || {};
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
      colon:false
    };
    const colItem = {
      span:12
    }
    /**
     * [getMyDate description]毫秒数时间转日期格式
     * @param   {[type]}  str [description]
     * @return  {[type]}      [description]
     * @author 李树冬
     * @version [version]
     */
    function getMyDate(str){
      //补0操作
      function getzf(num){
         if(parseInt(num) < 10){
             num = '0'+num;
         }
         return num;
       }
      var oDate = new Date(str),
      oYear = oDate.getFullYear(),
      oMonth = oDate.getMonth()+1,
      oDay = oDate.getDate(),
      oHour = oDate.getHours(),
      oMin = oDate.getMinutes(),
      oSen = oDate.getSeconds(),
      oTime = oYear +'-'+ getzf(oMonth) +'-'+ getzf(oDay) +' '+ getzf(oHour) +':'+ getzf(oMin) +':'+getzf(oSen);//最后拼接时间
      return oTime;
    };
    const dataSource = [];
    const sonData = [{id:sonId, startPerson, abortPerson, sonPrice, sonCost, description,}];
    const serverData = [{ id:serverId, name, genre, reimbursementRatio, insuredAmount, deductible, subsidyAmount, numberDayIndemnity, quota, serverDescription,}];
    const sonColumns = [
      {
        title: '起始人数',
        dataIndex: 'startPerson',
        key: 'startPerson'
      }, {
        title: '截止人数',
        dataIndex: 'abortPerson',
        key: 'abortPerson'
      }, {
        title: '价格',
        dataIndex: 'sonPrice',
        key: 'sonPrice'
      }, {
        title: '成本',
        dataIndex: 'sonCost',
        key: 'sonCost'
      },{
        title: '描述',
        dataIndex: 'description',
        key: 'description'
      }
    ];
    const serverColumns = [
      {
      title: '服务子项名称',
      dataIndex: 'name',
      key: 'name',
      }, {
      title: '服务子项类型',
      dataIndex: 'genre',
      key: 'genre',
      }, {
      title: '报销比例',
      dataIndex: 'reimbursementRatio',
      key: 'reimbursementRatio',
      }, {
      title: '保额',
      dataIndex: 'insuredAmount',
      key: 'insuredAmount',
      },{
      title: '免赔额',
      dataIndex: 'deductible',
      key: 'deductible',
      },{
      title: '每天补贴金额',
      dataIndex: 'subsidyAmount',
      key: 'subsidyAmount',
      }, {
      title: '免赔期，天数',
      dataIndex: 'numberDayIndemnity',
      key: 'numberDayIndemnity',
      }, {
      title: '日限额',
      dataIndex: 'quota',
      key: 'quota',
      },{
      title: '描述',
      dataIndex: 'serverDescription',
      key: 'serverDescription',
      },
    ];

    //根据数组生成Cascader的options
    function arrayToOptions(array){
      const options = [];
      array.forEach((item)=>{
        options.push({value:item.id,label:item.customerName});
      })
      return options;
    }
    let customers = arrayToOptions(customerList);

    return (
      <span>
        <span onClick={this.showModalHandler}>
          { children }
        </span>
        <Modal
          title="派接单"
          visible={this.state.visible}
          onOk={this.okHandler}
          onCancel={this.hideModalHandler}
          style={{minWidth:'600px'}}
          width='70vw'

        >
          <div
            style={{height:this.state.disabled ? '60vh' : '45vh',overflow:'auto',padding:'0 10px'}}
          >
            <Form onSubmit={this.okHandler}>
              <Toggles name='报价单'>
                <Row >
                  <Col {...colItem}>
                    <FormItem label='客户名称' {...formItemLayout}>
                      {
                          getFieldDecorator('customerId',{
                            initialValue: [customerId],
                          })(<Cascader
                             placeholder=''
                             size='large'
                             disabled={this.state.disabled}
                             showSearch
                             options={customers}
                              />)
                     }
                    </FormItem>
                  </Col>
                  <Col {...colItem}>
                    <FormItem label='产品' {...formItemLayout}>
                     {
                       getFieldDecorator('product',{
                         initialValue:product,
                         rules: [{ required: true, message: '请输入产品名称!' }],
                       })(
                         <Select disabled={this.state.disabled} >
                           <Select.Option value="个税">个税</Select.Option>
                           <Select.Option value="体检">体检</Select.Option>
                           <Select.Option value="员工慰问">员工慰问</Select.Option>
                           <Select.Option value="委托服务费">委托服务费</Select.Option>
                           <Select.Option value="工资代收代付">工资代收代付</Select.Option>
                           <Select.Option value="工资服务费服">工资服务费服</Select.Option>
                           <Select.Option value="服装费">服装费</Select.Option>
                           <Select.Option value="服务费">服务费</Select.Option>
                           <Select.Option value="档案">档案</Select.Option>
                           <Select.Option value="证件工本费">证件工本费</Select.Option>
                           <Select.Option value="银行转账费">银行转账费</Select.Option>
                           <Select.Option value="工资营业税">工资营业税</Select.Option>

                         </Select>
                       )
                     }
                    </FormItem>
                  </Col>
                  <Col {...colItem}>
                    <FormItem label='价格' {...formItemLayout}>
                      {
                        getFieldDecorator('price',{
                          initialValue:price,
                        })( <InputNumber min={0} max={1000} step={20.00} size='large' disabled={this.state.disabled} style={{width:'100%'}}/>)
                      }
                    </FormItem>
                  </Col>
                  <Col {...colItem}>
                    <FormItem label='成本' {...formItemLayout}>
                      {
                        getFieldDecorator('cost',{
                          initialValue:cost,
                        })(<InputNumber min={0} max={1000} step={20.00} size='large' disabled={this.state.disabled} style={{width:'100%'}}/>)
                      }
                    </FormItem>
                  </Col>
                  <Col {...colItem}>
                    <FormItem label='服务描述' {...formItemLayout}>
                      {
                        getFieldDecorator('serviceDescription',{
                          initialValue:serviceDescription,
                        })(<Input size='large' disabled={this.state.disabled} type='textarea'/>)
                      }
                    </FormItem>
                  </Col>
                  <Col {...colItem}>
                    <FormItem label='生效时间' {...formItemLayout}>
                      {
                        getFieldDecorator('effectiveTime',{
                          initialValue:effectiveTime ? moment(getMyDate(effectiveTime), 'YYYY-MM-DD') : null,
                        })(<DatePicker size='large' disabled={this.state.disabled} placeholder='' style={{width:'100%'}}/>)
                      }
                    </FormItem>
                  </Col>
                </Row>
                <Row>
                  <Col {...colItem}>
                    <FormItem label='失效时间' {...formItemLayout}>
                      {
                        getFieldDecorator('deadTime',{
                          initialValue:deadTime ? moment(getMyDate(deadTime), 'YYYY-MM-DD') : null,
                        })(<DatePicker size='large' disabled={this.state.disabled} placeholder='' style={{width:'100%'}}/>)
                      }
                    </FormItem>
                  </Col>
                  <Col {...colItem}>
                    <FormItem
                     {...formItemLayout}
                      label='状态'
                     >
                      {
                        getFieldDecorator('status', {
                        initialValue: status,
                          rules: [{ required: true, message: '请选择状态!' }],
                      })(
                          <RadioGroup disabled={this.state.disabled}>
                            <Radio value='1'>有 效</Radio>
                            <Radio value='2'>失 效</Radio>
                          </RadioGroup>
                        )
                      }
                    </FormItem>
                  </Col>
                  <Col {...colItem}>
                    <FormItem
                     {...formItemLayout}
                      label='阶梯报价'
                     >
                      {
                        getFieldDecorator('ladderQuotation', {
                        initialValue: ladderQuotation,
                          rules: [{ required: true, message: '请选择阶梯报价!' }],
                      })(
                        <RadioGroup disabled={this.state.disabled} >
                          <Radio value='1'>人 均</Radio>
                          <Radio value='2'>总 价</Radio>
                          <Radio value='0'>无</Radio>
                        </RadioGroup>
                        )
                      }
                    </FormItem>
                  </Col>
                  <Col {...colItem}>
                    <FormItem
                      {...formItemLayout}
                        label='报价方式'
                      >
                      {
                        getFieldDecorator('priceTerms', {
                        initialValue: priceTerms,
                        rules: [{ required: true, message: '请选择报价方式!' }],
                      })(
                          <RadioGroup disabled={this.state.disabled}>
                            <Radio value='1'>年</Radio>
                            <Radio value='2'>月</Radio>
                          </RadioGroup>
                        )
                      }
                    </FormItem>
                  </Col>
                </Row>
              </Toggles>
            </Form>
            <div style={{display:this.state.disabled ? '' : 'none'}}>
              <Row gutter={12}>
                <Col span={12}>
                  <Table
                    dataSource={sonData}
                    size={'large'}
                    columns={sonColumns}
                    scroll={{ x: 200,}}
                    rowKey={record => record.id}
                    style={{marginTop:'24px'}}
                  />
                </Col>
                <Col span={12}>
                  <Table
                    dataSource={serverData}
                    size={'large'}
                    columns={serverColumns}
                    scroll={{ x: 800,}}
                    rowKey={record => record.id}
                    style={{marginTop:'24px'}}
                  />
                </Col>
              </Row>
            </div>

          </div>
        </Modal>
      </span>
    );
  }
}

export default Form.create()(AddModal);
